class User::TestController < ApplicationController

  #before_filter :auth

  #before_filter :complete_filter

  #配置缓存
  caches_page :test

  #$KCODE = 'u'
  #layout false
  
  layout "test" ,:except => "home"

  def index
    @tests = Survey.find(:all, :conditions => {:status => TEST_STATUS_FINISHED, :professional => false})
    render :layout => false
  end

  def home
    @org = current_user
  end

  def prof_surveys
    #@tests = Survey.find(:all, :conditions => {:status => TEST_STATUS_FINISHED, :professional => true})
    @keyword = params[:keyword]
    
    @types = SurveyType.find_by_org_id(current_user.id)
    if @types.size !=0
      @type_id=@types[0].id

      #@tests = Survey.paginate :per_page => 10,:page=>params[:page],
      #  :conditions => "name like '%" + (@keyword || "") + "%'"
      sql = "select t1.* from surveys t1, orgs_surveys t2 where t1.id = t2.survey_id and t2.org_id = #{session[CURRENT_USER_ID]} "
      #sql += " and t1.name like '%" + (@keyword || "") + "%' and t1.test_type_id = #{@type_id}"
      sql += " and t1.test_type_id = #{@type_id}"
      @tests = Survey.paginate_by_sql(sql,{:per_page => 20, :page=> params[:page]})
      @system_surveys=Survey.find(:all ,:conditions=>{:t_type=>TEST_TYPE_PROF , :status =>TEST_STATUS_FINISHED })
      @all_tests=Survey.find_by_sql("select t1.* from surveys t1, orgs_surveys t2 where t1.id = t2.survey_id and t2.org_id = #{session[CURRENT_USER_ID]} ")
      @test_num=@all_tests.size
      render :layout => false #"user/paper_style"
    else
      redirect_to("/user/test/home")
    end
  end

  def prof_surveys_by_type
    @type_id = params["type_id"]
    @types = SurveyType.find_by_org_id(current_user.id)
    
    sql = "select t1.* from surveys t1, orgs_surveys t2 where t1.id = t2.survey_id and t2.org_id = #{session[CURRENT_USER_ID]} "
    unless @type_id == ""
      sql += " and t1.test_type_id = #{@type_id}"
    end
    @system_surveys=Survey.find(:all ,:conditions=>{:t_type=>TEST_TYPE_PROF , :status =>TEST_STATUS_FINISHED })
    @tests = Survey.paginate_by_sql(sql,{:per_page => 20, :page=> params[:page]})
    @all_tests=Survey.find_by_sql("select t1.id, t1.name from surveys t1, orgs_surveys t2 where t1.id = t2.survey_id and t2.org_id = #{session[CURRENT_USER_ID]} ")
    @test_num=@all_tests.size
    render "prof_surveys", :layout => false #"user/paper_style"
  end

  #用户资料没有完善就让他完善
  def complete_info
    @user = User.find(session[CURRENT_USER_ID])
    @test = Survey.find(params[:id])
    flash[:test_id] = params[:id]
    
    if !User.info_completed?(session[CURRENT_USER_ID])
      if @test.t_type == TEST_TYPE_PROF
        render :template => "/user/test/complete_info", :layout => "surveys/prof_surveys"
      else
        render   :layout => "surveys/prof_surveys"#:template => "/user/test/complete_info"
      end
    else
      redirect_to(:action => "test", :id => params[:id])
    end
  end  

  def test
   @user=current_user
    @test = Survey.find(params[:id])
    if @test.t_type == TEST_TYPE_TREND
      render :template => "user/test/trend_test" ,  :layout => "surveys/prof_surveys"
    elsif @test.t_type == TEST_TYPE_MANY_TREND
      render :template => "user/test/many_trend_test" , :layout => false
    elsif @test.t_type == TEST_TYPE_COUNT
      render :template => "user/test/count_test" ,  :layout => "surveys/prof_surveys"
    elsif @test.t_type == TEST_TYPE_PROF
      if @test.has_part != 0
        @pages = @test.paging
        if @test.rg_method == "ruiwen"
          flash[:agenotice]="请准确填写被测者年龄，如：5岁填5，5岁半 填写5.5。每半岁一个年龄段。本量表适合于5到17岁"
        end
        render :template => "user/test/prof_survey",:layout => false
      else
        @survey = @test.paging_no_part

        respond_to do |format|
          format.html {render :template => "user/test/prof_survey_no_part",:layout => false}
          format.xml { render :xml => @test.to_xml }
        end
      end
    end
  end
 
   # 读出跳转测试 
  def jtest
   @test = Survey.find(params[:id])
  end
  
  #计算简单倾向测试结果
  def result
    #原始结果
    o_results = []
    @test = Survey.find(params[:test_id])
    @user = current_user
    #如果是重新测试
      if params[:re_test]=="yes"
         logger.debug "删除原来的测试报告.............(简单倾向测试)."
        #先把原来的测量报告删除
         #sql="delete from original_results where test_id="+params[:test_id]+" and user_id="+session[CURRENT_USER_ID].to_s
         #puts "++++======================sql is  :"+sql 
         #ActiveRecord::Base.connection.execute(sql)
        OriginalResult.delete_all(["survey_id = ? and user_id = ?", params[:test_id], session[CURRENT_USER_ID] ])
      end
    @user.just_test(@test)
    @user.save
    
    @questions=@test.questions
    @questions.each do |question|
      #得到该题对应的倾向
      trend=question.trend_scale
      #收集单选按钮的值
      choice_value = params["question"+question.id.to_s]["value"]
      o_results.push([trend, choice_value.to_i])
      #把测试结果保存到 original_results表中
      original_result=OriginalResult.new
      original_result.user_id=session[CURRENT_USER_ID]
      original_result.survey_id=params[:test_id]
      
#    u_t= UserTest.new
      
      original_result.question_id=question.id
      original_result.trend_id=question.trend_scale_id
      original_result.value=choice_value
      original_result.save
      # ==========保存 OK=============
    end
    @result = ApplicationHelper.trend_test_result(o_results)
    render :layout=> false
  end
  
  #从original_results 中显示 已经完成的 测试结果！
  def get_result
    @test = Survey.find(params[:id])
    if @test.t_type == TEST_TYPE_TREND
       redirect_to(:action=>"get_trend_result" ,:id=>params[:id])
    elsif @test.t_type == TEST_TYPE_COUNT
      redirect_to(:action=>"get_count_result" ,:id=>params[:id])
    elsif @test.t_type == TEST_TYPE_MANY_TREND
      redirect_to(:action=>"get_many_tresult" ,:id=>params[:id])
    end
  end
      #得到用户一经完成的简单倾向测试报告
  def get_trend_result
    @test = Survey.find(params[:id])
    @user = current_user
    sql ="select test_id, user_id, trend_id, sum(value) v from original_results where test_id="+
    params[:id].to_s+" and user_id="+session[CURRENT_USER_ID].to_s+" group by trend_id order by v desc"
    @or_results=OriginalResult.find_by_sql(sql)
    @r_trend=TrendScale.find(@or_results[0].trend_id)
  end
  
  def get_count_result
    @test = Survey.find(params[:id])
    @user = current_user
    sql ="select id , test_id, user_id, value  from original_results where test_id=63 "
    @or_results=OriginalResult.find_by_sql(sql)
    @norms=@test.norms
    @result=Norm.new
      for n in @test.norms
        if @or_results[0].value.to_i >= n.begin_num && @or_results[0].value.to_i < n.end_num
          @result=n
        break
        end
      end
   @result
  end
  
  def get_many_tresult
  #用于复杂倾向测试
    @test=Survey.find(params[:id])
    @user = current_user
    @parts=@test.parts
    @trends=@test.trend_scales
    #首先查出 每一章节每一种倾向的得分........
    # 先找出每一章节的 每一种倾向的最高得分 存到 @trend_original_results
    sql1="select  user_id , test_id , trend_id , part_id , Max(value) value from original_results
          where test_id = "+@test.id.to_s+"  and user_id="+@user.id.to_s+" group by part_id"
    @trend_original_results = OriginalResult.find_by_sql(sql1)
    
    # 不区分章节 整个测试的每一种倾向的 得分  用于统计该测试中最可能的倾向产生总体报告
    @all_trends_results=OriginalResult.find_by_sql(
      "select  user_id , test_id , trend_id , sum(value) from original_results
          where test_id = "+@test.id.to_s+" and user_id="+@user.id.to_s+"
          group by trend_id")
     #所有结果的统计
     @pt_original_results=[]
     for part in @parts
     sql2="select  user_id , test_id , trend_id , part_id , sum(value) value from original_results
          where test_id = "+@test.id.to_s+"  and user_id="+@user.id.to_s+" and part_id="+part.id.to_s+" group by 
          trend_id order by trend_id "
       @pt_original_results << OriginalResult.find_by_sql(sql1)   
    end 
  end
  

=begin #用户重新测试 
  def re_test
      logger.debug "删除原来的测试报告.............."
      #先把原来的测量报告删除
      OriginalResult.delete_all(["test_id = ? and user_id = ?", params[:id], session[CURRENT_USER_ID] ])
     redirect_to(:action=>"test" , :id=>params[:id])
  end
=end 
  #按数组中元素的出现次数排反序
  #接收参数： Array, 返回： Array([["ruby", 3], ["java", 2]])
  def sort_by_item_times(array)
    hash = Hash.new
    for a in array
      count = 0
      for b in array
          if a == b then
            count = count + 1
          end
      end
      hash[a] = count
    end
    hash.sort {|a, b| b[1] <=> a[1]}
  end

  #计分测试
  def count_test
    @test = Survey.find(params[:id])
  end

  #计分测试结果
  def count_result
   results_hash =[]
   
   @test = Survey.find(params[:test_id])
   @user = current_user
   logger.debug ">>>>>>>>>>>>>>>>>#{params[:retest]}"
  #如果是重新测试
    if params[:re_test]=="yes"
      logger.debug "删除原来的测试报告.............(测试)"
      #先把原来的测量报告删除
      #sql="delete from original_results where test_id="+params[:test_id]+" and user_id="+session[CURRENT_USER_ID].to_s
     #puts "++++======================sql is  :"+sql 
       #ActiveRecord::Base.connection.execute(sql)
      OriginalResult.delete_all(["test_id = ? and user_id = ?", params[:test_id], session[CURRENT_USER_ID] ])
    end
    @user.just_test(@test)
    @user.save
    questions=@test.questions
    questions.each do |question|
      #收集单选按钮的值 
      coefficient=question.coefficient
      choice_value = params["question"+question.id.to_s]["result"];
      results_hash << [coefficient,choice_value.to_i]
      #查出常模
      @norms=@test.norms
    end
    @score=get_score(results_hash).to_i
    @result=Norm.new
      for n in @norms
        if @score >= n.begin_num && @score <n.end_num
          @result=n
        break
        end
      end
   @result
   #把测试结果保存到 original_results表中  每一个测试 只有一条报存记录！
      original_result=OriginalResult.new
      original_result.user_id=session[CURRENT_USER_ID]
      original_result.survey_id=params[:test_id]
      original_result.value=@score #保存时 把整个测试的题目总得分保存！
      original_result.save
      render  :layout => "surveys/prof_surveys"
 end
  
  
 def get_score(arr)
    @score=0
    count=0
    for a in arr
     count=a[0]*a[1]
       @score=@score+count
       count=0
    end 
    @score
  end
  
  def many_trend_result
    @test = Survey.find(params[:test_id])
    @parts=@test.parts
    @trends=@test.trend_scales
    @reports=[]
    @user = current_user
     if params[:re_test]=="yes"
       logger.debug "删除原来的测试报告.............(复杂倾向测试)."
      OriginalResult.delete_all(["survey_id = ? and user_id = ?", params[:test_id], session[CURRENT_USER_ID] ])
    end
    @user.just_test(@test)
    @user.save
    
    for part in @parts
      @partReport=[]  #每部分结果
      #对提交参数处理  开始分析结果！
        for q in part.questions
          result_report=Report.new
          q_id="question"+q.id.to_s
          value=params["part"+part.id.to_s][q_id][:value]
          answer=params["part"+part.id.to_s][q_id][:answer]
          trend_id=params["part"+part.id.to_s][q_id][:trend_scales_id]
          report=Report.find(:first, :conditions => ["part_id = ? and trend_scales_id= ?",part.id.to_s ,trend_id])
          #result_report 是把用户测试的数据统计为 report  形式  如果需要 在另外保存用户数据  现在 暂时没有保存
            if report!=nil # result_report != nil
                result_report=report
                result_report.value=report.value+(value.to_i)*(answer.to_i)
                @partReport <<  result_report
            end
        end
      # 此时得到的@reports 是 一个 report 的集合的集合 其中为每一道题目都保存一条report记录
        # ********@reports 是该算法中 最重要的一个数据集合*********
      @reports <<  @partReport
    end 
    
    for report in @reports
      for rep in report
        @or=OriginalResult.new
        #@or.question_id =rep.q_id
        @or.user_id=session[CURRENT_USER_ID]  # 现在 不保存 user信息是为了 测试方便
        @or.survey_id = params[:test_id].to_i
        @or.part_id =rep.part_id
        @or.trend_id =rep.trend_scales_id
        @or.value =rep.value
        @or.save
      end
    end
#============================存储 OriginalResult END =========== 
# ===下面为 每一部分 每一种倾向 统计结果 并统计出整个测试中不考虑章节的每一种倾向的得分=======
#==================该部分程序 写的比较乱 待日后再做修改...====================
    
    @trendReports=[] #这里存放的是  分章节的 每一部分的每种倾向的 得分
     for part in @parts
       for trend in @trends # 对倾向作循环 每一种倾向 有一个 报告
        trendreport=[]
        trendreport << trend
        trendreport << 0
        trendreport << part
        @trendReports << trendreport
      end 
    end
    
    @part_trend_reprt=[] # [part[  [trend ,value , part] ;:.... ]]
    for part in @parts
      part_report_arr=[]
       for trend in @trends # 对倾向作循环 每一种倾向 有一个 报告
        trendreport=[]
        trendreport << trend
        trendreport << 0
        trendreport << part
        part_report_arr << trendreport
      end 
      @part_trend_reprt << part_report_arr
    end
    
   @items=[]# 存放整个测试中不考虑章节的每一种倾向的得分 items[item[[倾向][value]];
                                                                                      # item[[倾向][value]] ]
    for trend in @trends
      item=[]
      item << trend
      item << 0
      @items << item
    end 

    for report  in @reports
      for rep  in report
      
        for tr in @trendReports
           if  tr[0].id==rep.trend_scales_id&&tr[2].id==rep.part_id
            tr[1]=tr[1]+rep.value
           end 
        end
        
        for item in @items
           if  item[0].id==rep.trend_scales_id
               item[1]=item[1]+rep.value
           end 
        end 
        
        for ptr in @part_trend_reprt
           for pr in ptr
             if pr[0].id==rep.trend_scales_id&&pr[2].id==rep.part_id
                 pr[1]=pr[1]+rep.value
             end 
           end 
        end
         
      end   
   end
     #===========end=============
    #===对结果作排序+=========
    #不考虑 章节对每一种倾向的 得分 排序  数据结构和@item 一样！
    @sortItems=@items
    for i in 0...@sortItems.size
      for j in i...@sortItems.size
        if @sortItems[i][1] < @sortItems[j][1]
          t_item=@sortItems[i]
          @sortItems[i]=@sortItems[j]
          @sortItems[j]=t_item
        end 
      end
    end
    #对每一个章节的 每一种倾向 排序 
    @sortPTReport=@part_trend_reprt
    for p_report  in @sortPTReport
      for i in 0...p_report.size
        for j in i...p_report.size
          if p_report[i][1] < p_report[j][1]
              t_p_report=p_report[i]
              p_report[i]=p_report[j]
              p_report[j]=t_p_report
          end 
        end
      end
   end
    #==========排序end ======
    #对items根据value值排序
    @items = @items.sort { |b,a| a[1] <=> b[1]  }
    @trendReports.each do |it|
    puts "================="+it[1].to_s+"===================="
    end
    session[:items]=@items
    render :layout => "surveys/prof_surveys"
  end

  #================================================
  #         计算多种倾向测试的结果
  #================================================
  def many_trend_result_datas
   @items=session[:items]
   headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8
   render :layout => false
  end
  
  #专业量表结果(暂时废弃，以后可能会用，清不要删除)
  def prof_result111

    @test = Survey.find(params[:test_id])
    @user = current_user
    logger.debug ">>>>>>>>>>>>>>>>>#{params[:retest]}"
    #如果是重新测试
    if params[:retest]
      logger.debug "删除原来的测试报告.............."
      #先把原来的测量报告删除
      OriginalResult.delete_all(["survey_id = ? and user_id = ?", params[:test_id], session[CURRENT_USER_ID] ])
    end
    @user.just_test(@test)
    @user.save
    
    params[:question_id].each do |q_id|
      #收集每道题的分值／记录原始分
      @or = OriginalResult.new
      @or.question_id = q_id
      @or.test_id = params[:test_id].to_i
      @or.part_id = params["question" + q_id][:part_id].to_i
      @or.dimen_id = params["question" + q_id][:dimen_id].to_i

      @or.user_id = session[CURRENT_USER_ID]

      @or.value = params["question" + q_id]["value"].to_i
      @or.save
    end

    #统计分数
    @total = OriginalResult.sum(:value, :conditions => ["test_id = ?", params[:test_id]])
    @avg = OriginalResult.average(:value, :conditions => ["test_id = ?", params[:test_id]])

    @original_results = OriginalResult.find_all_by_test_id(params[:test_id].to_i)

    @part_results = OriginalResult.find_by_sql(
      [ "select part_id, sum(value) total, avg(value) avg from original_results
          where test_id = ? group by part_id",
        params[:test_id].to_i
      ]
    )

    @dimen_results = OriginalResult.find_by_sql(
      [ "select dimen_id, sum(value) total, avg(value) avg from original_results
          where test_id = ? group by dimen_id",
        params[:test_id].to_i
      ]
    )

    #查询量表对应的常模
=begin
    @norms = Norm.find_by_curr_user(params[:test_id], current_user)

    @results = []
    @norms.each do |n|

      @dimen_results.each do |d|
        if n.item_id == d.dimen_id

          if d.avg.to_i >= (n.specimen_avg - 2*n.specimen_standard_deviation) and d.avg.to_i <= (n.specimen_avg + 2*n.specimen_standard_deviation)
            result = "正常"
          else
            result = "不正常"
          end
          @results << [Dimen.find(n.item_id), result, d.avg, n.specimen_avg, n.specimen_standard_deviation]
        end
      end
    end
=end

    @norms = Norm.cross_table(params[:test_id])
    render :layout => false
  end

  def update_user
    @user = User.find(params[:user][:id])
    @user.is_complete = USER_INFO_COMPLETED
    respond_to do |format|
      if @user.update_attributes!(params[:user])
          flash[:test_id] = params[:test_id]
          format.html { redirect_to(:action => "test", :id => params[:test_id])}
      else
          flash[:error_notice] = "保存失败"
          format.html { redirect_to(:action => "complete_info", :id => @user)}
      end
    end
  end

  #专业量表结果
  def prof_result

    @test = Survey.find(params[:survey_id])
    @user = current_user

    username = params[:username].strip == "" ? "匿名" : params[:username]
    @test_record = SurveyRecord.new
    @test_record.age=params[:age]
    @test_record.gender=params[:gender]
    @test_record.perfession=params[:perfession]
    @test_record.edu_status=params[:edu_status]
    @test_record.testname=@test.name
    @test_record.testtime=params[:timer]
    @test_record.username = username 
    @test_record.survey_id = params[:survey_id]
    @test_record.org = @user
    @test_record.save!

    params[:question_id].each do |q_id|
      #收集每道题的分值／记录原始分
      @or = OriginalResult.new
      @or.survey_id=params[:survey_id]
      @or.question_id = q_id
      @or.part_id = params["question-#{q_id}-part"].to_i if @test.has_part
      @or.value = Float(params["question-#{q_id}-value"])
      @or.choice_num = params["question-#{q_id}-choice"]
      @or.test_record_id = @test_record.id
      @or.save
    end
    render :layout => false
  end
  
  def help
    render :layout => false
  end
  

  
end



